<?php
// 创建 WebSocket 服务器监听 8000 端口
$webSocketServer = new Swoole\WebSocket\Server("0.0.0.0", 8000);

// 创建 UDP 服务器监听 4444 端口
$udpServer = $webSocketServer->addListener("0.0.0.0", 4444, SWOOLE_UDP);

// 存储所有 WebSocket 客户端连接
$clients = new SplObjectStorage();

// 处理 WebSocket 连接打开事件
$webSocketServer->on('open', function (Swoole\WebSocket\Server $server, $request) use (&$clients) {
    echo "WebSocket 客户端连接: {$request->fd}\n";
    // 存储客户端连接
    $clients->attach($request);
});

// 处理 WebSocket 消息事件
$webSocketServer->on('message', function (Swoole\WebSocket\Server $server, $frame) {
    echo "收到 WebSocket 消息: {$frame->data}\n";
    // 可以在这里处理来自 WebSocket 客户端的消息
    //foreach ($server->connections as $fd) {
    //    $server->push($fd, $frame->data);
    //}
    $server->push($frame->fd, "Server: {$frame->data}");
});

// 处理 WebSocket 连接关闭事件
$webSocketServer->on('close', function (Swoole\WebSocket\Server $server, $fd) use (&$clients) {
    echo "WebSocket 客户端断开: {$fd}\n";
    // 移除客户端连接
    foreach ($clients as $client) {
        if ($client->fd === $fd) {
            $clients->detach($client);
            break;
        }
    }
});

// 处理 UDP 数据接收事件
$udpServer->on('packet', function (Swoole\Server $server, $data, $clientInfo) use (&$clients) {
    echo "收到 UDP 数据: " . bin2hex($data) . " 来自: {$clientInfo['address']}:{$clientInfo['port']}\n";
    
    // 广播 UDP 数据给所有 WebSocket 客户端
    foreach ($clients as $client) {
        try {
            $server->push($client->fd, $data, SWOOLE_WEBSOCKET_OPCODE_BINARY);
            echo "数据已发送到客户端: {$client->fd}\n";
        } catch (Exception $e) {
            echo "发送数据到客户端 {$client->fd} 失败: " . $e->getMessage() . "\n";
        }
    }
});

// 启动服务器
echo "服务器启动: WebSocket 端口 8000, UDP 端口 4444\n";
$webSocketServer->start();

?>
